<!--
 * @Descripttion: 编辑批发价
 * @Author: xiao li
 * @Date: 2021-01-30 09:22:31
 * @LastEditors: xiao li
 * @LastEditTime: 2021-05-12 09:40:09
-->
<template>
    <div class="lb-add-classify">
        <top-nav :title="navTitle" :isBack="true"/>
        <div class="page-main">
          <lb-tips>
            <p>注：若用户选择的商品数量高于商家设置的最高数量范围，则享受的折扣依然为最大折扣。例如：商家设置100件以内打9折，用户加购数量为101件时，折扣为9折。</p>
          </lb-tips>
          <div class="mt-md mb-lg"></div>
          <el-form @submit.native.prevent :model="subForm" ref='subForm' :rules="subFormRules" label-width="120px">
              <el-form-item label="选择商品规格" prop="spe_id">
                <el-select v-model="subForm.spe_id" placeholder="请选择">
                    <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.spe_content"
                    :value="item.id">
                    </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="批发价规则" prop="range" v-for="(item,index) in subForm.range" :key='index'>
                <block>数量</block>
                <el-input class="min" v-model.number="item.min" type="text"></el-input>
                <block>-</block>
                <el-input class="min mr-lg" v-model.number="item.max" type="text"></el-input>
                <block>折扣</block>
                <el-input v-model="item.discount" class="ml-sm" type="text" placeholder="小于10，保留1位小数"><template slot="append">折</template></el-input>
                <lb-button class="ml-lg" type='danger' icon='el-icon-delete' @click="toAddItem(2,index)">删除</lb-button>
              </el-form-item>
              <el-form-item>
                <lb-button type='primary' icon='el-icon-plus' @click="toAddItem(1)">新增</lb-button>
              </el-form-item>
              <el-form-item>
                <div class="space-body"></div>
                  <lb-button type='primary' @click="submitInfo">{{$t('action.submit')}}</lb-button>
                  <lb-button @click="$router.back(-1)">{{$t('action.back')}}</lb-button>
              </el-form-item>
          </el-form>
        </div>
    </div>
</template>

<script>
export default {
  data () {
    let validateRange = (rule, value, callback) => {
      if (this.subForm.range.length === 0) {
        callback(new Error('请新增批发价规则'))
      } else {
        callback()
      }
    }
    return {
      navTitle: '',
      subForm: {
        id: 0,
        goods_id: 0,
        spe_id: '',
        range: [{min: '', max: '', discount: ''}]
      },
      subFormRules: {
        spe_id: {required: true, type: 'number', message: '请选择商品规格', trigger: 'blur'},
        range: {required: true, validator: validateRange, trigger: 'blur'}
      },
      options: []
    }
  },
  created () {
    let {id, cid = 0} = this.$route.query
    this.subForm.goods_id = id
    this.getSelectOptions()
    if (cid) {
      this.subForm.id = cid
      this.getDetail()
    }
    this.navTitle = this.$t(cid ? 'menu.WholesaleEdit' : 'menu.WholesaleAdd')
  },
  methods: {
    /**
     * @method: 获取下拉框的值
     * @param {*} id
     */
    async getSelectOptions () {
      let {goods_id: id} = this.subForm
      let {code, data} = await this.$api.getBaseSpePrice({goods_id: id})
      if (code !== 200) return
      this.options = this.options.concat(data)
    },
    /**
     * @method: 详情
     */
    async getDetail () {
      let {id} = this.subForm
      let {code, data} = await this.$api.wholesaleInfo({id})
      if (code !== 200) return
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    /**
     * @method: 新增/删除批发价
     */
    async toAddItem (key, index) {
      if (key === 2) {
        this.subForm.range.splice(index, 1)
      } else {
        this.subForm.range.push({min: '', max: '', discount: ''})
      }
    },
    /**
     * @method: 添加/编辑
     */
    async submitInfo () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        for (let key in subForm.range) {
          let index = key * 1 + 1
          let minNum = key * 1 === 0 ? 0 : subForm.range[key * 1 - 1].max
          if (!/^\+?[1-9]\d*$/.test(subForm.range[key].min) || subForm.range[key].min < minNum + 1) {
            this.$message.error(`批发价规则第${index}条数据：(开始数量) 请输入大于${minNum}的整数`)
            return
          } else if (!/^\+?[1-9]\d*$/.test(subForm.range[key].max) || subForm.range[key].max < subForm.range[key].min + 1) {
            this.$message.error(`批发价规则第${index}条数据：(结束数量) 请输入大于${subForm.range[key].min}的整数`)
            return
          } else if (!/^(([0-9][0-9]*)|(([0]\.\d{1}|[0-9][0-9]*\.\d{1})))$/.test(subForm.range[key].discount) || subForm.range[key].discount * 1 > 10) {
            this.$message.error(`批发价规则第${index}条数据：(折扣) 请输入0-10之间的数字，最多保留1位小数`)
            return
          }
        }
        let methodModel = subForm.id ? 'wholesaleUpdate' : 'wholesaleAdd'
        let {code} = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
        this.$router.back(-1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .lb-add-classify{
      width: 100%;
      .page-main{
      .el-form{
          width: 100%;
          .el-form-item{
            margin-bottom: 24px;
              .el-select{
                  width: 538px;
              }
              .el-input{
                width: 230px;
              }
              .el-input.min{
                width: 100px;
              }
            }
        }
      }
  }
</style>
